<template>
  <div class="panel-container home-right-inside">
    <el-tabs v-model="activeTab" class="tabs-header aside-area" type="border-card">
      <el-tab-pane label="组件设置" name="1" class="comp-setting" :data-selectedWidget="selectedWidgetInfo(designer)" :data-category="designer?.selectedWidget?.category">
        <!--什么场景下使用?--category字段不存在-->
        <template v-if="!!(designer.selectedWidget)">
          <template v-if="(!designer.selectedWidget?.category)">
            <el-form
                :model="optionModel"
                size="small"
                label-position="left"
                label-width="80px"
                class="setting-form"
                @submit.prevent
            >
              <el-collapse v-model="widgetActiveCollapseNames" class="setting-collapse">
                <template v-if="true">
                  <el-collapse-item
                      name="1"
                      title="常见属性"
                      v-if="showCollapse(commonProps)"
                  >
                    <template v-for="(editorName, propName) in commonProps">
                      <div class="connect-wrap">
                        <component
                            :designer="designer"
                            :option-model="optionModel"
                            :selected-widget="selectedWidget"
                            v-if="hasPropEditor(propName, editorName)"
                            :is="getPropEditor(propName, editorName)"
                        />
                      </div>
                    </template>
                  </el-collapse-item>
                </template>
                <template v-if="true">
                  <el-collapse-item
                      title="2"
                      name="高级属性"
                      v-if="showCollapse(advProps,1)"
                  >
                    <template v-for="(editorName, propName) in advProps">
                      <div class="connect-wrap">
                        <component
                            v-if="hasPropEditor(propName, editorName)"
                            :is="getPropEditor(propName, editorName)"
                            :designer="designer"
                            :selected-widget="selectedWidget"
                            :option-model="optionModel"/>
                      </div>
                    </template>
                  </el-collapse-item>
                </template>
                <template v-if="true">
                  <el-collapse-item
                      name="3"
                      title="事件属性"
                      v-if="showEventCollapse() && showCollapse(eventProps)"
                  >
                    <!--                  事件属性-->
                    <template v-for="(editorName, propName) in eventProps">
                      <div class="connect-wrap">
                        <component
                            v-if="hasPropEditor(propName, editorName)"
                            :is="getPropEditor(propName, editorName)"
                            :designer="designer"
                            :selected-widget="selectedWidget"
                            :option-model="optionModel"
                        />
                      </div>
                    </template>
                  </el-collapse-item>
                </template>
              </el-collapse>
            </el-form>
          </template>
          <template v-if="(!!designer.selectedWidget?.category)">
            <el-form
                :model="optionModel"
                size="small"
                @submit.prevent
                label-width="100px"
                label-position="left"
                class="setting-form"
            >
              <el-collapse v-model="widgetActiveCollapseNames" class="setting-collapse">
                <!--开发环境显示组件名称&正式环境隐藏组件名称-->
                <template v-if="isProd">
                  <el-collapse-item
                      name="1"
                      title="常见属性"
                      v-if="showCollapse(commonProps)"
                  >
                    <template v-for="(editorName, propName) in commonProps">
                      <div class="connect-wrap" v-if="selectedWidgetInfo(designer)&&hasPropEditor(propName, editorName)">
                        <component
                            :designer="designer"
                            :option-model="optionModel"
                            :selected-widget="selectedWidget"
                            :is="getPropEditor(propName, editorName)"
                        />
                      </div>
                    </template>
                  </el-collapse-item>
                </template>
                <template v-if="true">
                  <el-collapse-item
                      name="2"
                      title="高级属性"
                      v-if="showCollapse(advProps)"
                  >
                    <template v-for="(editorName, propName) in advProps">
                      <div class="connect-wrap" v-if="selectedWidgetInfo(designer)&&hasPropEditor(propName, editorName)">
                        <!--                      {{getPropEditor(propName, editorName)}}-->
                        <component
                            :designer="designer"
                            :option-model="optionModel"
                            :selected-widget="selectedWidget"
                            :is="getPropEditor(propName, editorName)"
                        />
                      </div>
                    </template>
                  </el-collapse-item>
                </template>
                <template v-if="false">
                  <el-collapse-item
                      name="3"
                      title="事件属性"
                      v-if="showEventCollapse() && showCollapse(eventProps)"
                  >
                    <template v-for="(editorName, propName) in eventProps">
                      <div class="connect-wrap">
                        常见属性-{{ getPropEditor(propName, editorName) }}-{{ hasPropEditor(propName, editorName) }}
                      </div>
                    </template>
                  </el-collapse-item>
                </template>
              </el-collapse>
            </el-form>
          </template>
        </template>
        <template v-else>
          <el-empty description="暂无数据"></el-empty>
        </template>
      </el-tab-pane>
      <el-tab-pane label="父级设置" name="2" class="parent-setting">
        <ParentSetting :designer="designer" :form-config="formConfig"/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import emitter from "@/utils/designer/emitter";
import PropertyEditors from './property-editor'
import WidgetProperties from './propertyRegister'
import ParentSetting from './property-editor/parent-setting.vue'
import {propertyRegistered} from "@/scenes/templateDetails/modules/homeRight/propertyRegister";

const {COMMON_PROPERTIES, ADVANCED_PROPERTIES, EVENT_PROPERTIES} = WidgetProperties;


export default {
  name: "HomeRight",

  componentName: "HomeRight",

  mixins: [emitter],

  components: {
    ...PropertyEditors,
    ParentSetting,
  },

  props: {
    designer: Object,
    selectedWidget: Object,
    formConfig: Object,
    globalDsv: {
      type: Object,
      default: () => ({})
    },
  },

  inject: ['getDesignerConfig'],

  data() {
    return {
      isProd: false,
      designerConfig: this.getDesignerConfig(),
      activeTab: '1',
      widgetActiveCollapseNames: ['1', '2', '3'],
      formActiveCollapseNames: ['1', '2'],
      commonProps: COMMON_PROPERTIES,
      advProps: ADVANCED_PROPERTIES,
      eventProps: EVENT_PROPERTIES,
      eventHeader: '',
      curEventName: '',
      eventHandlerCode: '',
      subFormChildWidgetFlag: false,
      showWidgetEventDialogFlag: false,
    }
  },

  computed: {
    optionModel: {
      get() {
        return this.selectedWidget?.options
      },

      set(newValue) {
        this.selectedWidget.options = newValue
      }
    },

  //  判断选中的组件是否空对象
    selectedWidgetInfo() {
      return function (row) {
        return !this.$lodash.isEmpty(row)
      }
    },

  },

  created() {
    this.isProd = (process.env.NODE_ENV) === 'development'
    this.on$('editEventHandler', (eventParams) => {
      this.editEventHandler(eventParams[0], eventParams[1])
    })

    this.designer.handleEvent('form-css-updated', (cssClassList) => {
      this.designer.setCssClassList(cssClassList)
    })
  },

  mounted() {
    if (!this.designer.selectedWidget) {
      this.activeTab = "1"
    } else {
      this.activeTab = "2"
    }
  },

  methods: {
    showEventCollapse() {
      if (this.designerConfig['eventCollapse'] === undefined) {
        return true
      }
      return !!this.designerConfig['eventCollapse']
    },

    hasPropEditor(propName, editorName) {
      if (!editorName) {
        return false
      }
      /* alert组件注册了两个type属性编辑器，跳过第一个type属性编辑器，只显示第二个alert-type属性编辑器！！ */
      if (propName.indexOf('-') <= -1) {
        let uniquePropName = this.selectedWidget?.type + '-' + propName
        if (propertyRegistered(uniquePropName)) {
          return false
        }
      }

      let originalPropName = propName.replace(this.selectedWidget.type + '-', '')  //去掉组件名称前缀-，如果有的话！！
      return this.designer.hasConfig(this.selectedWidget, originalPropName)
    },

    getPropEditor(propName, editorName) {
      let originalPropName = propName.replace(this.selectedWidget.type + '-', '')  //去掉组件名称前缀-，如果有的话！！
      let ownPropEditorName = `${this.selectedWidget?.type}-${originalPropName}-editor`;
      //局部注册的属性编辑器组件
      if (!!this.$options.components[ownPropEditorName]) {
        return ownPropEditorName
      }
      return !!this.$root.$options.components[ownPropEditorName] ? ownPropEditorName : editorName  //全局注册的属性编辑器组件
    },

    showCollapse(propsObj) {
      let result = false
      for (let propName in propsObj) {
        if (!propsObj.hasOwnProperty(propName)) {
          continue
        }
        if (this.hasPropEditor(propName, propsObj[propName])) {
          result = true
          break
        }
      }
      return result
    },

    editEventHandler(eventName, eventParams) {
      this.curEventName = eventName
      this.eventHeader = `${this.optionModel.name}.${eventName}(${eventParams.join(', ')}) {`
      this.eventHandlerCode = this.selectedWidget.options[eventName] || ''

      // 设置字段校验函数示例代码
      if ((eventName === 'onValidate') && (!this.optionModel['onValidate'])) {
        this.eventHandlerCode = "  /* sample code */\n  /*\n  if ((value > 100) || (value < 0)) {\n    callback(new Error('error message'))  //fail\n  } else {\n    callback();  //pass\n  }\n  */"
      }

      this.showWidgetEventDialogFlag = true
    },

    saveEventHandler() {
      const codeHints = this.$refs.ecEditor.getEditorAnnotations()
      let syntaxErrorFlag = false
      if (!!codeHints && (codeHints.length > 0)) {
        codeHints.forEach((chItem) => {
          if (chItem.type === 'error') {
            syntaxErrorFlag = true
          }
        })

        if (syntaxErrorFlag) {
          this.$message.error('数据异常');
          return
        }
      }

      this.selectedWidget.options[this.curEventName] = this.eventHandlerCode
      this.showWidgetEventDialogFlag = false
    },

  },

  watch: {
    'designer.selectedWidget': {
      handler(val) {
        if (!!val) {
          this.activeTab = "1"
        }
      }
    },

    'selectedWidget.options': {  //组件属性变动后，立即保存表单JSON！！
      deep: true,
      handler() {
        this.designer.saveCurrentHistoryStep()
      }
    },

    formConfig: {
      handler() {
        this.designer.saveCurrentHistoryStep()
      },
      deep: true,
    },

  },
}
</script>

<style lang="scss" scoped>
@import "./assets/style";
</style>